package com.shizhanzhe.gxb.circle.fragment;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shizhanzhe.gxb.R;
import com.shizhanzhe.gxb.WXLoginActivity;
import com.shizhanzhe.gxb.base.UserBean;
import com.shizhanzhe.gxb.circle.adapter.PDDSourceAdapter;
import com.shizhanzhe.gxb.circle.adapter.TuiGoodsAdapter;
import com.shizhanzhe.gxb.circle.bean.Material;
import com.shizhanzhe.gxb.circle.bean.TuiGoods;
import com.shizhanzhe.gxb.home.bean.PDDURL;
import com.shizhanzhe.gxb.home.dialog.ShareWxPopupWindow;
import com.shizhanzhe.gxb.url.Path;
import com.shizhanzhe.gxb.utils.DrawLongPictureUtil;
import com.shizhanzhe.gxb.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.gxb.utils.Util;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * @author YJ
 * @date 2019/1/8
 */
public class CircleFormFragment extends Fragment {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl)
    SmartRefreshLayout srl;
    @BindView(R.id.no_data)
    ImageView noData;
    Unbinder unbinder;
    private String id;
    private PDDSourceAdapter mpddAdapter;
    private TuiGoodsAdapter mGoodsAdapter;
    private int page;
    private DrawLongPictureUtil mDrawLongPictureUtil;
    private String resultPath = "";
    ProgressDialog dialog;

    public static CircleFormFragment newInstance(String id) {

        Bundle args = new Bundle();
        args.putString("id", id);
        CircleFormFragment fragment = new CircleFormFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            id = getArguments().getString("id");
        }

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_circle_form, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initData() {
        dialog = new ProgressDialog(getContext());
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条的形式为圆形转动的进度条
        dialog.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialog.setMessage("正在生成...Loading");
        recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        recycler.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
        if ("1".equals(id)) {
            mGoodsAdapter = new TuiGoodsAdapter(getContext());
            recycler.setAdapter(mGoodsAdapter);
            mGoodsAdapter.setListener(new TuiGoodsAdapter.TuiGoodsListener() {
                @Override
                public void copyText(String text) {
                    if (UserBean.uid != 0) {
                        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        cm.setText(text);
                        Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                    } else {
                        startActivity(new Intent(getContext(), WXLoginActivity.class));
                    }
                }

                @Override
                public void extension(final TuiGoods.DataBean item) {
                    if (UserBean.uid != 0) {
                        OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.PDDURL(UserBean.uid, item.getGoods_id()), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                            @Override
                            public void onsendJson(String json) {
                                final PDDURL pddurl = new Gson().fromJson(json, PDDURL.class);
                                final ShareWxPopupWindow wxPopupWindow = new ShareWxPopupWindow(getActivity());
                                wxPopupWindow.setWxListener(new ShareWxPopupWindow.ShareWxListener() {
                                    @Override
                                    public void shareFriend() {
                                        wxPopupWindow.dismiss();
//                                        dialog.show();
//                                        mDrawLongPictureUtil = new DrawLongPictureUtil(getContext());
//                                        mDrawLongPictureUtil.setListener(new DrawLongPictureUtil.Listener() {
//                                            @Override
//                                            public void onSuccess(final String path) {
//                                                getActivity().runOnUiThread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        dialog.dismiss();
//                                                        Toast.makeText(getContext(), "长图已生成", Toast.LENGTH_SHORT).show();
//                                                        resultPath = path;
//                                                        Log.d("_____",resultPath);
//
//                                                        Wechat.ShareParams sp = new Wechat.ShareParams();
////                                                sp.setImagePath(Environment.getExternalStorageDirectory() + "/test/gxbinvite.jpg");
//                                                        sp.setImagePath(resultPath);
//                                                        sp.setShareType(Platform.SHARE_IMAGE);
//                                                        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
//                                                        weChat.share(sp);
//                                                    }
//                                                });
//                                            }
//
//                                            @Override
//                                            public void onFail() {
//                                                getActivity().runOnUiThread(new Runnable() {
//                                                    @Override
//                                                    public void run() {
//                                                        Toast.makeText(getActivity(), "长图生成失败", Toast.LENGTH_SHORT).show();
//                                                    }
//                                                });
//                                            }
//                                        });
//                                        if (Arrays.asList(item.getImg().split(",")).size()>0) {
//                                            Info info = new Info();
//                                            info.setContent(item.getTitle());
//                                            info.setImage(Arrays.asList(item.getImg().split(",")).get(0));
//                                            info.setPromotion_amount(item.getPromotion_amount());
//                                            info.setUrl(pddurl.getData().getWe_app_web_view_short_url());
//                                            mDrawLongPictureUtil.setData(info);
//                                            mDrawLongPictureUtil.startDraw();
//                                        }
                                        Wechat.ShareParams sp = new Wechat.ShareParams();
                                        sp.setTitle(item.getTitle());
                                        sp.setText(item.getContent());
                                        sp.setUrl(pddurl.getData().getWe_app_web_view_short_url());
                                        sp.setImageUrl(Path.BASE_URL + Arrays.asList(item.getImg().split(",")).get(0));
                                        sp.setShareType(Platform.SHARE_WEBPAGE);
                                        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                                        weChat.share(sp);
                                    }

                                    @Override
                                    public void shareCircle() {
                                        wxPopupWindow.dismiss();
                                        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                                        cm.setText(item.getContent());
                                        Toast.makeText(getContext(), "推广文本已复制", Toast.LENGTH_SHORT).show();
                                        WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
                                        sp.setTitle(item.getTitle());
                                        sp.setUrl(pddurl.getData().getWe_app_web_view_short_url());
                                        sp.setImageUrl(Path.BASE_URL + Arrays.asList(item.getImg().split(",")).get(0));
                                        sp.setShareType(Platform.SHARE_WEBPAGE);
                                        Platform Moments = ShareSDK.getPlatform(WechatMoments.NAME);
                                        Moments.share(sp);
                                    }

                                    @Override
                                    public void shareSave() {
                                    }
                                });
                                wxPopupWindow.showDown2(recycler);
                            }
                        });
                    } else {
                        startActivity(new Intent(getContext(), WXLoginActivity.class));
                    }
                }
            });
        } else {
            mpddAdapter = new PDDSourceAdapter(getContext());
            recycler.setAdapter(mpddAdapter);
            mpddAdapter.setListener(new PDDSourceAdapter.PDDSourceListener() {
                @Override
                public void copyText(String text) {
                    if (UserBean.uid != 0) {
                        ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        cm.setText(text);
                        Toast.makeText(getContext(), "复制成功", Toast.LENGTH_SHORT).show();
                    } else {
                        startActivity(new Intent(getContext(), WXLoginActivity.class));
                    }
                }

                @Override
                public void extension(final Material.DataBeanX.DataBean item) {
                    if (UserBean.uid != 0) {
                        final ShareWxPopupWindow wxPopupWindow = new ShareWxPopupWindow(getActivity());
                        wxPopupWindow.setWxListener(new ShareWxPopupWindow.ShareWxListener() {
                            @Override
                            public void shareFriend() {
                                wxPopupWindow.dismiss();
                                Wechat.ShareParams sp = new Wechat.ShareParams();
                                sp.setTitle("网购宝邀请您加入");
                                sp.setText(item.getContent());
                                sp.setUrl(Path.invitereg(UserBean.uid));
                                sp.setImageUrl(Path.BASE_URL + item.getImg().split(",")[0]);
                                sp.setShareType(Platform.SHARE_WEBPAGE);
                                Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                                weChat.share(sp);
                            }

                            @Override
                            public void shareCircle() {
                                wxPopupWindow.dismiss();
                                ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                                cm.setText(item.getContent());
                                Toast.makeText(getContext(), "推广文本已复制", Toast.LENGTH_SHORT).show();
                                WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
                                sp.setTitle("网购宝邀请您加入");
                                sp.setUrl(Path.invitereg(UserBean.uid));
                                sp.setImageUrl(Path.BASE_URL + Arrays.asList(item.getImg().split(",")).get(0));
                                sp.setShareType(Platform.SHARE_WEBPAGE);
                                Platform Moments = ShareSDK.getPlatform(WechatMoments.NAME);
                                Moments.share(sp);
                            }

                            @Override
                            public void shareSave() {
                                //保存图文
                                Util.GetImageInputStream(getContext(), Arrays.asList(item.getImg().split(",")));
                                ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                                cm.setText(item.getContent());
                                Toast.makeText(getContext(), "图文保存成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                        wxPopupWindow.showDown(recycler);
                    } else {
                        startActivity(new Intent(getContext(), WXLoginActivity.class));
                    }
                }
            });
        }
        getList();
        srl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getList();
            }
        });
        srl.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getList();
            }
        });
    }

    private void getList() {
        if ("1".equals(id)) {
            OkHttpDownloadJsonUtil.downloadJson(getContext(), Path.tuiGoods(UserBean.uid, page), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

                @Override
                public void onsendJson(String json) {
                    srl.finishRefresh();
                    srl.finishLoadMore();
                    if (!"1".equals(json) && !"2".equals(json)) {
                        try {
                            Gson gson = new Gson();
                            TuiGoods tuiGoods = gson.fromJson(json, TuiGoods.class);
                            if (tuiGoods.getData().size() > 0) {
                                mGoodsAdapter.updateData(page, tuiGoods.getData());
                            } else {
                                if (page == 1) {
                                    noData.setVisibility(View.VISIBLE);
                                } else {
                                    Toast.makeText(getContext(), "暂时没有更多了", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (Exception e) {
                            Toast.makeText(getContext(), "数据异常", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            String url = "";
            if ("2".equals(id)) {
                url = Path.material(page);
            } else {
                url = Path.novice(page);
            }
            OkHttpDownloadJsonUtil.downloadJson(getContext(), url, new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

                @Override
                public void onsendJson(String json) {
                    if (srl != null) {
                        srl.finishRefresh();
                        srl.finishLoadMore();
                    }
                    if (!"1".equals(json) && !"2".equals(json)) {
                        try {
                            Gson gson = new Gson();
                            Material material = gson.fromJson(json, Material.class);
                            if (material.getData().getData().size() > 0) {
                                mpddAdapter.updateData(page, material.getData().getData());
                            } else {
                                if (page == 1) {
                                    noData.setVisibility(View.VISIBLE);
                                } else {
                                    Toast.makeText(getContext(), "暂时没有更多了", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } catch (Exception e) {
                            Toast.makeText(getContext(), "数据异常", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
